package com.example.springboot.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.springboot.common.HoneyLogs;
import com.example.springboot.common.LogType;
import com.example.springboot.common.Result;
import com.example.springboot.entity.Orders;
import com.example.springboot.entity.User;
import com.example.springboot.service.OrderService;
import com.example.springboot.service.UserService;
import com.example.springboot.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.UUID;

/**
 * 功能:
 * 作者: sdj
 * 日期: 2024/12/8 22:23
 */
@CrossOrigin
@RestController
@RequestMapping("/orders")
public class OrdersController {
    @Autowired
    OrderService ordersService;

    @Autowired
    UserService userService;

    @HoneyLogs(operation = "订单",type = LogType.ADD)
    @PostMapping("/add")
    public Result add(@RequestBody Orders orders){
        try {
            User currentUser = TokenUtils.getCurrentUser();
            orders.setUserid(currentUser.getId());
            orders.setDate(DateUtil.today());
            orders.setNo(IdUtil.fastSimpleUUID());
            ordersService.save(orders);   //保存一个数据
        }catch (Exception e){
            if (e instanceof DuplicateKeyException){
                return Result.error("插入数据库错误");
            }else {
                return  Result.error("系统错误");
            }
        }
        return Result.success();
    }

    @HoneyLogs(operation = "订单",type = LogType.UPDATE)
    @PostMapping("/update")
    public Result update(@RequestBody Orders orders){
        ordersService.updateById(orders);   //根据id更新数据
        return Result.success();
    }


    @GetMapping("/selectAll")
    public Result selectAll(){
        List<Orders> userList=ordersService.list(new QueryWrapper<Orders>().orderByDesc("id"));  //查询所有数据根据id排序
        return Result.success(userList);
    }

    @GetMapping("/selectOrderss")
    public Result selectOrderss(){
        QueryWrapper<Orders> queryWrapper = new QueryWrapper<Orders>().orderByDesc("id");
        queryWrapper.eq("open","1");
        List<Orders> userList=ordersService.list(queryWrapper);  //查询所有数据根据id排序
        return Result.success(userList);
    }

    @GetMapping("/selectById/{id}")
    public Result selectById(@PathVariable Integer id){
        Orders orders=ordersService.getById(id); //根据id查询
        return Result.success(orders);
    }

    @HoneyLogs(operation = "订单",type = LogType.DELETE)
    @PostMapping("/delete/{id}")
    public Result deleteById (@PathVariable Integer id){
        boolean b = ordersService.removeById(id);
        if (b){
            return Result.success();
        }else {
            return Result.error("删除数据失败");
        }
    }

    @HoneyLogs(operation = "订单",type = LogType.BATCH_DELETE)
    @PostMapping("/delete/batch")
    public Result deleteByList(@RequestBody List<Integer> ids){
        boolean b = ordersService.removeBatchByIds(ids);
        if (b){
            return Result.success();
        }else {
            return Result.error("删除数据失败");
        }
    }


    /*
    * pageNum:当前页码
    * pageSize:每页显示多少条数据
    * 联表查询
    * */
    @GetMapping("/selectByPage")
    public Result selectByPage(@RequestParam String name,
                               @RequestParam Integer pageNum,
                               @RequestParam Integer pageSize
                              ){
        QueryWrapper<Orders> queryWrapper = new QueryWrapper<Orders>().orderByDesc("id");
        queryWrapper.like(StrUtil.isNotBlank(name),"name",name);

        Page<Orders> page = ordersService.page(new Page<>(pageNum, pageSize), queryWrapper);  //多条件分页模糊查询
        List<Orders> records = page.getRecords(); //获取查询结果
        for (Orders record : records) {
            User user = userService.getById(record.getUserid());
            if (user != null) record.setUser(user.getName());
        }
        return Result.success(page);
    }
}
